/** 
* @file allocator.h
* Interface for kernel memory allocation engine (kernel heap).
* Inspired by JamesM's kernel development tutorials.
*
* Copyrights 2010 Michal Saman, m.saman@designplus.cz.
* This source code is release under the Apache License 2.0.
* http://www.apache.org/licenses/LICENSE-2.0
*/

#ifndef ALLOCATOR_H
#define ALLOCATOR_H

#include <stdint.h>
#include <lib/ordered_array.h>

/** Inicial size of heap - max count of allocated objects. */
#define HEAP_INDEX_SIZE		0x20000U
#define HEAP_MAGIC			0xAC
#define HEAP_MIN_SIZE		0x70000U

/**
* Heap memory block header structure.
*/
typedef struct {
	uint8_t		magic;		//**< Magic number, used for indetification and error checking. */
	uint8_t		is_hole;	//**< Definition of memory block, 1 - empty/hole, 0 - used/block. */
	uint32_t	size;		//**< Size of memory block. */
} header_t;

/** 
* Heap memory block footer structure.
*/
typedef struct {
	uint8_t	magic;		//**< Cointains same magic number as in header_t. */
	header_t	*header;	//**< Pointer to block header. */
} footer_t;

/**
* Heap structure.
*/
typedef struct {
	ord_array_t		directory;		//**< Directory of memory blocks ordered by size. */
	uint32_t		start_address;	//**< Start of allocated space for heap. */
	uint32_t		end_address;	//**< End of allocated space for heap. */
	uint32_t		size;			//**< Size of heap in bytes */
	uint32_t		max_address;	//**< Maximum address the heap can be expanded to. */
	uint8_t			supervisor;		//**< Supervisor mode. Allocated extra pages map as supervisor-only. */
	uint8_t			readonly;		//**< Readonly mode. Allocated extra pages map as read-only. */
} heap_t;

extern heap_t* init_allocator(uint32_t heap_size, uint32_t heap_start);
extern void create_heap(heap_t* heap, uint32_t start, uint32_t end, uint32_t max, uint8_t supervisor, uint8_t readonly);
extern void *alloc(uint32_t size, uint8_t page_align, heap_t *heap);
extern void free(void *p, heap_t *heap);

#endif
